<template>
  <div class="bug-list">
    <div class="header">
      <h2>Bug 列表</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加 Bug
      </el-button>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="待修复" name="pending">
        <bug-table 
          :bugs="bugStore.pendingBugs" 
          :loading="loading"
          @fix="handleFix"
          @view="handleView"
        />
      </el-tab-pane>
      
      <el-tab-pane label="修复中" name="fixing">
        <bug-table 
          :bugs="bugStore.fixingBugs" 
          :loading="loading"
          @fix="handleFix"
          @view="handleView"
        />
      </el-tab-pane>
      
      <el-tab-pane label="已修复" name="fixed">
        <bug-table 
          :bugs="bugStore.fixedBugs" 
          :loading="loading"
          @fix="handleFix"
          @view="handleView"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加 Bug 对话框 -->
    <el-dialog v-model="showAddDialog" title="添加 Bug" width="600px">
      <el-form :model="newBug" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="newBug.title" placeholder="请输入 Bug 标题" />
        </el-form-item>
        
        <el-form-item label="描述" required>
          <el-input 
            v-model="newBug.description" 
            type="textarea" 
            :rows="4" 
            placeholder="请详细描述 Bug 问题"
          />
        </el-form-item>
        
        <el-form-item label="严重程度" required>
          <el-select v-model="newBug.severity">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="严重" value="critical" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="相关文件">
          <el-input v-model="newBug.file" placeholder="如：src/components/Login.vue" />
        </el-form-item>
        
        <el-form-item label="行号">
          <el-input-number v-model="newBug.line" :min="1" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddBug">确定</el-button>
      </template>
    </el-dialog>

    <!-- Bug 详情对话框 -->
    <el-dialog v-model="showViewDialog" title="Bug 详情" width="800px">
      <div v-if="selectedBug" class="bug-detail">
        <div class="bug-header">
          <h3>{{ selectedBug.title }}</h3>
          <el-tag :type="getSeverityType(selectedBug.severity)">
            {{ getSeverityText(selectedBug.severity) }}
          </el-tag>
          <el-tag :type="getStatusType(selectedBug.status)">
            {{ getStatusText(selectedBug.status) }}
          </el-tag>
        </div>
        
        <div class="bug-info">
          <p><strong>描述：</strong></p>
          <p>{{ selectedBug.description }}</p>
          
          <div v-if="selectedBug.file" class="bug-location">
            <p><strong>位置：</strong> {{ selectedBug.file }}
              <span v-if="selectedBug.line">:{{ selectedBug.line }}</span>
            </p>
          </div>
          
          <div class="bug-time">
            <p><strong>创建时间：</strong> {{ formatDate(selectedBug.createdAt) }}</p>
            <p><strong>更新时间：</strong> {{ formatDate(selectedBug.updatedAt) }}</p>
          </div>
          
          <div v-if="selectedBug.solution" class="bug-solution">
            <p><strong>解决方案：</strong></p>
            <pre>{{ selectedBug.solution }}</pre>
          </div>
          
          <div v-if="selectedBug.error" class="bug-error">
            <p><strong>错误信息：</strong></p>
            <pre class="error-message">{{ selectedBug.error }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useBugStore } from '@/stores/bug'
import { ClaudeCodeService } from '@/services/claudeCode'
import type { Bug } from '@/types/bug'
import BugTable from './BugTable.vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const bugStore = useBugStore()

const activeTab = ref('pending')
const loading = ref(false)
const showAddDialog = ref(false)
const showViewDialog = ref(false)
const selectedBug = ref<Bug | null>(null)

const newBug = reactive({
  title: '',
  description: '',
  severity: 'medium' as Bug['severity'],
  file: '',
  line: undefined as number | undefined
})

const handleFix = async (bug: Bug) => {
  loading.value = true
  try {
    // 检查 Claude CLI（模拟实现）
    const claudeService = ClaudeCodeService.getInstance()
    const cliCheck = await claudeService.checkClaudeCLI()
    
    if (!cliCheck.installed || !cliCheck.configured) {
      ElMessage.error('Claude CLI 未安装或未配置，请先运行: claude login')
      loading.value = false
      return
    }
    
    bugStore.updateBugStatus(bug.id, 'fixing')
    bugStore.setFixingBug(bug.id)
    
    // 调用 Claude Code SDK
    const result = await claudeService.fixBug(bug)
    
    if (result.success) {
      bugStore.updateBugStatus(
        bug.id, 
        'fixed', 
        result.message
      )
      ElMessage.success(`Bug 修复成功！提交哈希: ${result.commitHash || 'N/A'}`)
    } else {
      bugStore.updateBugStatus(
        bug.id, 
        'pending', 
        undefined, 
        result.error
      )
      ElMessage.error(`Bug 修复失败: ${result.error}`)
    }
  } catch (error) {
    console.error('修复错误:', error)
    bugStore.updateBugStatus(bug.id, 'pending', undefined, error instanceof Error ? error.message : '未知错误')
    ElMessage.error(`修复过程中出现错误: ${error instanceof Error ? error.message : '未知错误'}`)
  } finally {
    loading.value = false
    bugStore.setFixingBug(null)
  }
}

const handleView = (bug: Bug) => {
  selectedBug.value = bug
  showViewDialog.value = true
}

const handleAddBug = () => {
  if (!newBug.title || !newBug.description) {
    return
  }
  
  bugStore.addBug({
    title: newBug.title,
    description: newBug.description,
    severity: newBug.severity,
    status: 'pending',
    file: newBug.file || undefined,
    line: newBug.line
  })
  
  // 重置表单
  newBug.title = ''
  newBug.description = ''
  newBug.severity = 'medium'
  newBug.file = ''
  newBug.line = undefined
  
  showAddDialog.value = false
}

const getSeverityType = (severity: Bug['severity']) => {
  const types = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    critical: 'danger'
  }
  return types[severity]
}

const getSeverityText = (severity: Bug['severity']) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高',
    critical: '严重'
  }
  return texts[severity]
}

const getStatusType = (status: Bug['status']) => {
  const types = {
    pending: 'info',
    fixing: 'warning',
    fixed: 'success',
    failed: 'danger'
  }
  return types[status]
}

const getStatusText = (status: Bug['status']) => {
  const texts = {
    pending: '待修复',
    fixing: '修复中',
    fixed: '已修复',
    failed: '失败'
  }
  return texts[status]
}

const formatDate = (date: Date) => {
  return new Intl.DateTimeFormat('zh-CN').format(date)
}
</script>

<style scoped>
.bug-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.bug-detail {
  line-height: 1.6;
}

.bug-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.bug-header h3 {
  margin: 0;
}

.bug-info p {
  margin: 8px 0;
}

.bug-location {
  margin: 15px 0;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.bug-time {
  margin: 15px 0;
  font-size: 14px;
  color: #666;
}

.bug-solution {
  margin: 15px 0;
}

.bug-solution pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
}

.bug-error {
  margin: 15px 0;
}

.error-message {
  background-color: #fef0f0;
  color: #f56c6c;
  padding: 10px;
  border-radius: 4px;
  white-space: pre-wrap;
}
</style>